<template>
  <m-window-frame
    :title="$t('LY集成')"
    style="height: 100%"
    class="v-LY-window"
    :okLoading="okLoading"
    :cancelText="$t('关 闭')"
    :okText="$t('保 存')"
    @cancel="handleCancel"
    @ok="handleSave"
  >
    <div class="_main g-fd-c">
      <div class="_main-content">
        <div
          ref="mainBox"
          class="_main-box"
        >
          <el-row
            v-for="item in dataList"
            :key="item.id"
            :gutter="16"
            class="operation-item"
          >
            <el-col :span="6">
              <div class="label">设计模型:</div>
              <el-dropdown
                :ref="(el: any) => handleDropdownRef(el, item.id + '#' + 'modelId')"
                trigger="click"
                placement="bottom-start"
                style="height: 24px"
                :popper-options="popperOptions"
                :class="{ error: errValueKeys.has(item.id + '#' + 'modelId') }"
              >
                <div
                  class="dropdown-content"
                  @click="selectedDropDownId = item.id + '#' + 'modelId'"
                >
                  <img
                    v-if="getModelInfoById(item.modelId)?.icon"
                    :src="getModelInfoById(item.modelId)?.icon"
                    width="16"
                    height="16"
                    onerror="this.src='statics/images/sysml/Stereotype.svg'"
                    alt=""
                  />
                  <span class="text g-one-line">{{ getModelInfoById(item.modelId)?.label }}</span>
                  <img
                    src="statics/icons/app/iconlist2.png"
                    alt=""
                    class="_btn"
                  />
                </div>
                <template #dropdown>
                  <ModelDropdown
                    v-if="selectedDropDownId === item.id + '#' + 'modelId'"
                    :list="resourcePerformerOptionList"
                    :infiniteScroll="true"
                    @scroll-change="(page: number, pageSize: number, keyword: string) => loadOptionList(page, pageSize, keyword,'ResourcePerformer')"
                    @changeOption="(val: DropdownItem) => changeOption(item, 'modelId', val)"
                  ></ModelDropdown>
                </template>
              </el-dropdown>
            </el-col>
            <el-col :span="6">
              <div class="label">信号:</div>
              <el-dropdown
                :ref="(el: any) => handleDropdownRef(el, item.id + '#' + 'signalId')"
                trigger="click"
                placement="bottom-start"
                style="height: 24px"
                :popper-options="popperOptions"
                :class="{ error: errValueKeys.has(item.id + '#' + 'signalId') }"
              >
                <div
                  class="dropdown-content"
                  @click="selectedDropDownId = item.id + '#' + 'signalId'"
                >
                  <img
                    v-if="getModelInfoById(item.signalId)?.icon"
                    :src="getModelInfoById(item.signalId)?.icon"
                    width="16"
                    height="16"
                    onerror="this.src='statics/images/sysml/Stereotype.svg'"
                    alt=""
                  />
                  <span class="text g-one-line">{{ getModelInfoById(item.signalId)?.label }}</span>
                  <img
                    src="statics/icons/app/iconlist2.png"
                    alt=""
                    class="_btn"
                  />
                </div>
                <template #dropdown>
                  <ModelDropdown
                    v-if="selectedDropDownId === item.id + '#' + 'signalId'"
                    :list="resourceSignalOptionList"
                    :infiniteScroll="true"
                    @scroll-change="(page: number, pageSize: number, keyword: string) => loadOptionList(page, pageSize, keyword,'ResourceSignal')"
                    @changeOption="(val: DropdownItem) => changeOption(item, 'signalId', val)"
                  ></ModelDropdown>
                </template>
              </el-dropdown>
            </el-col>
            <el-col :span="6">
              <div class="label">{{ simulationLabel }}:</div>
              <el-input
                v-model="item.entityId"
                :class="{ error: errValueKeys.has(item.id + '#' + 'entityId') }"
              ></el-input>
            </el-col>
            <el-col :span="6">
              <div class="label">控制指令:</div>
              <el-input
                v-model="item.messageTypeId"
                :class="{ error: errValueKeys.has(item.id + '#' + 'messageTypeId') }"
              ></el-input>
            </el-col>
            <el-button
              class="g-ai-c delete-button"
              @click="deleteData(item.id)"
            >
              <img
                src="statics/icons/table/icondelete2.svg"
                width="14"
              />
              <span style="margin-left: 4px">{{ $t("删除") }}</span>
            </el-button>
          </el-row>
        </div>
      </div>
      <el-button
        class="g-ai-c add-button"
        @click="addData"
      >
        <img
          src="statics/icons/app/add.svg"
          width="14"
        />
        <span style="margin-left: 4px">{{ $t("添加") }}</span>
      </el-button>
    </div>
  </m-window-frame>
</template>
<script lang="ts" setup>
import MWindowFrame from "@/common/ipcWindow/WindowFrame.vue";
import { ref, computed, watch, nextTick, onBeforeMount } from "vue";
import { Params, CloseData } from "./index";
import { useRoute } from "vue-router";
import { ipcWindowUtil } from "@/mdesign-lib/mdesign-app.umd.js";
import ModelDropdown from "@/modules/model/modals/relationCriteria/components/ModelDropdown/index.vue";
import { archService } from "@/mdesign-lib/mdesign-app.umd.js";
import { LingYunDataDto } from "@/mdesign-lib/mdesign-app.umd.js";
import { modelService } from "@/mdesign-lib/mdesign-app.umd.js";
import { getUid } from "@/util/common";

interface DropdownItem {
  label: string;
  value: string;
  icon?: string;
}

const route = useRoute();
let projectId = "";
const dropdownRef = ref<{ [key: string]: any }>({});
const size = 1000;
let current = 1;
// let maxScrollTop = 0;
// const bottomLimit = 30;
const dataList = ref<LingYunDataDto[]>([]);
const modelInfoMap = ref(new Map<string, DropdownItem>());
const resourcePerformerOptionList = ref<DropdownItem[]>([]);
const resourceSignalOptionList = ref<DropdownItem[]>([]);
let resourcePerformerDataLoaded = ref(false);
let resourceSignalDataLoaded = ref(false);
const selectedDropDownId = ref("");
const okLoading = ref(false);
const errValueKeys = ref(new Set<string>());
const mainBox = ref<HTMLElement | null>();
const simulationLabel = ref("仿真模型名称");

watch(
  () => route.fullPath,
  () => {
    const routeQuery = route.query as unknown;
    const query = routeQuery as Params;
    projectId = query.projectId;
  },
  { immediate: true }
);

const popperOptions = computed(() => {
  return {
    modifiers: [
      {
        name: "applyStyles",
        effect: ({ state }) => {
          state.elements.popper.style.width = `${Math.max(state.elements.reference.offsetWidth, 110)}px`;
        }
      }
    ]
  };
});

onBeforeMount(async () => {
  await getLingYunType();
  getList();
});

const getLingYunType = async () => {
  const type = await archService.getLingYunType(projectId);
  if (!type) {
    simulationLabel.value = "仿真模型ID";
  }
};

const getList = async () => {
  const { data, modelInfos } = await archService.queryLingYunList(projectId, current, size);
  dataList.value = dataList.value.concat(data);

  if (modelInfos?.length) {
    const formatModelInfos = modelInfos.map(item => ({
      icon: modelService.getModelIcon(projectId, item.icon),
      label: item.name,
      value: item.id
    }));
    formatModelInfos.forEach(item => !modelInfoMap.value.get(item.value) && modelInfoMap.value.set(item.value, item));
  }
};

const addData = () => {
  const validated = validate();
  if (!validated) return;
  dataList.value.push({
    entityId: "",
    messageTypeId: "",
    modelId: "",
    signalId: "",
    id: getUid()
  });
  scrollToBottom(mainBox.value);
};

const deleteData = (id: string) => {
  const index = dataList.value.findIndex(item => item.id === id);
  if (index > -1) {
    dataList.value.splice(index, 1);
  }
};

const validate = () => {
  const errKeys = new Set<string>();
  dataList.value.forEach(data => {
    const keys = Object.keys(data);
    for (let key of keys) {
      const value = data[key];
      if (!value) {
        errKeys.add(data.id + "#" + key);
      }
    }
  });
  errValueKeys.value = errKeys;
  return !errKeys.size;
};

const getModelInfoById = (id: string) => {
  return modelInfoMap.value.get(id);
};

// const handleScroll = (event:Event) => {
//   const container = event.target as HTMLDivElement;

//   const { clientHeight, scrollHeight, scrollTop } = container;
//   const toBottom = scrollHeight - clientHeight - scrollTop;

//   if (toBottom <= bottomLimit && scrollTop > maxScrollTop) {
//     // console.log('trigger scroll', toBottom, scrollTop);
//     maxScrollTop = scrollTop + toBottom;
//     current++;
//     getList();
//   }
// };

const scrollToBottom = (element?: HTMLElement | null) => {
  nextTick(() => {
    element && element.scrollTo({ top: element.scrollHeight });
  });
};

const loadOptionList = async (page: number, pageSize: number, keyword: string, type: "ResourcePerformer" | "ResourceSignal") => {
  let moreBtnCondition = "UAF::Resources::Taxonomy::ResourcePerformer";
  let optionListRef = resourcePerformerOptionList;
  let dataLoaded = resourcePerformerDataLoaded;
  if (type === "ResourcePerformer") {
    moreBtnCondition = "UAF::Resources::Taxonomy::ResourcePerformer";
    optionListRef = resourcePerformerOptionList;
    dataLoaded = resourcePerformerDataLoaded;
  } else if (type === "ResourceSignal") {
    moreBtnCondition = "UAF::Resources::Connectivity::ResourceSignal";
    optionListRef = resourceSignalOptionList;
    dataLoaded = resourceSignalDataLoaded;
  } else {
    return;
  }
  if (page === 1) {
    dataLoaded.value = false;
  }
  if (dataLoaded.value) return;
  const res = await modelService.getSelectOptionsAndAllCount({
    checkMethod: "",
    instanceId: moreBtnCondition,
    key: "",
    moreBtnCondition: moreBtnCondition,
    projectId,
    page,
    size: pageSize,
    keyword
  });
  const data = res.list;
  if (page === 1) {
    optionListRef.value = data;
  } else {
    optionListRef.value = optionListRef.value.concat(data);
  }

  if (optionListRef.value.length === res.allCount) {
    dataLoaded.value = true;
  }
};

const handleDropdownRef = (el: any, key: string | number) => {
  dropdownRef.value[key] = el;
};

const changeOption = async (item: LingYunDataDto, valueKey: string, option: DropdownItem) => {
  item[valueKey] = option.value;
  if (!modelInfoMap.value.get(option.value)) {
    modelInfoMap.value.set(option.value, option);
  }
  const currentDropDownRef = dropdownRef.value[item.id + "#" + valueKey];
  currentDropDownRef.handleClose();
};

const handleSave = async () => {
  const validated = validate();
  if (!validated) return;
  okLoading.value = true;
  await archService.saveLingYunList(projectId, dataList.value).finally(() => (okLoading.value = false));

  handleclose({ success: true });
};

function handleclose(data: CloseData) {
  ipcWindowUtil.closeWindow(data);
}
function handleCancel() {
  handleclose({ success: false });
}
</script>
<style lang="scss">
.v-LY-window {
  height: 100%;
  display: flex;
  flex-direction: column;
  .el-input {
    flex: 1;
    overflow: hidden;
    .el-input__wrapper {
      box-shadow: none;
      border: 1px solid rgba(0, 0, 0, 0.15);
      padding-top: 0;
      padding-bottom: 0;
      transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
    }
    &.error {
      .el-input__wrapper {
        border-color: #f56c6c;
      }
    }
  }
  ._btn {
    display: inline-block;
    cursor: pointer;
  }
  .el-dropdown {
    flex: 1;
    overflow: hidden;
    border: 1px solid rgba(0, 0, 0, 0.15);
    transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
    &.error {
      border-color: #f56c6c;
    }
    .el-tooltip__trigger {
      flex: 1;
      overflow: hidden;
    }
  }
  .dropdown-content {
    display: flex;
    align-items: center;
    height: 24px;
    padding: 0 7px;
    span {
      display: inline-block;
      font-size: 12px;
      margin-right: 4px;
    }
  }
  .text {
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
    line-height: 14px;
    flex: 1;
  }
  ._main {
    height: 100%;
  }
  .add-button {
    color: rgba(0, 0, 0, 0.65);
    width: calc(100vw - 48px);
    border: 1px dashed #cacaca;
    margin: 0 24px 12px 24px;
  }
  ._main-content {
    flex: 1;
    padding: 24px;
    overflow: hidden;
    ._main-box {
      overflow-y: auto;
      height: 100%;
      padding: 12px;
      padding-right: 78px;
      border: 1px solid #e4e4e4;
    }
    .operation-item {
      position: relative;
      margin-bottom: 18px;
      .delete-button {
        border: 0;
        position: absolute;
        top: 50%;
        right: -58px;
        transform: translateY(-50%);
        padding: 5px 8px;
        color: rgba(0, 0, 0, 0.65);
      }
    }
    .el-col {
      display: flex;
      align-items: center;
      .label {
        text-align: right;
        margin-right: 4px;
        min-width: 50px;
        color: rgba(0, 0, 0, 0.65);
      }
    }
  }
}
</style>
